const { ByteQueue } = require('../utils/byteQueue');

class FrontendHandler {
    constructor(frontendSocket, backendSocket, ledInterface) {
        this.frontendSocket = frontendSocket;
        this.backendSocket = backendSocket;
        this.ledInterface = ledInterface;
        this.byteQueue = new ByteQueue(100);
    }

    // 处理从飞控软件接收的数据
    handleData(data) {
        try {
            // 1. 检查是否是内容传输开始
            if (this.matchBytes(data, this.ledInterface.FeiKongContentStart)) {
                this.handleContentStart();
                return;
            }

            // 2. 检查是否是内容传输过程
            if (this.ledInterface.FeiKongIsMatch) {
                // 检查是否是下一段内容
                if (this.matchBytes(data, this.ledInterface.FeiKongContentNext) && 
                    !this.matchBytes(data, this.ledInterface.FeiKongLastSend) &&
                    data.length > 8) {
                    
                    // 根据数据包中的索引构造响应
                    const replyData = this.ledInterface.getFeiKongDataContentReplay(data[8]);
                    this.frontendSocket.write(Buffer.from(replyData));
                    return;
                }

                // 3. 检查是否是内容传输结束
                if (this.matchBytes(data, this.ledInterface.FeiKongLastSend)) {
                    // 构造最后的响应
                    this.frontendSocket.write(Buffer.from(this.ledInterface.FeiKongLastSendReply));
                    this.ledInterface.FeiKongIsMatch = false;
                    return;
                }
            }

            // 检查是否是控制命令
            if (this.isControlCommand(data)) {
                this.handleControlCommand(data);
                return;
            }

            // 处理文本内容
            this.processQueueData();
        } catch (error) {
            console.error('处理数据错误:', error);
            this.closeConnection();
        }
    }

    // 检查是否是控制命令
    isControlCommand(data) {
        // 检查是否匹配开关机命令
        return (
            this.matchBytes(data, this.ledInterface.FeiKongPowerOn) ||
            this.matchBytes(data, this.ledInterface.FeiKongPowerOff)
        );
    }

    // 处理控制命令
    handleControlCommand(data) {
        // 处理开机命令
        if (this.matchBytes(data, this.ledInterface.FeiKongPowerOn)) {
            console.log('收到开机命令');
            this.ledInterface.InnerControl = 1;
            this.backendSocket.write(this.ledInterface.FeiKongPowerOn);
            return;
        }

        // 处理关机命令
        if (this.matchBytes(data, this.ledInterface.FeiKongPowerOff)) {
            console.log('收到关机命令');
            this.ledInterface.InnerControl = 2;
            this.backendSocket.write(this.ledInterface.FeiKongPowerOff);
            return;
        }
    }

    // 处理队列中的数据
    async processQueueData() {
        // 获取单个数据包
        const dataPackets = await this.ledInterface.getSingleFeiKongDataFromQueue();
        
        if (!dataPackets || dataPackets.length === 0) {
            return;
        }

        // 处理每个数据包
        for (const packet of dataPackets) {
            // 检查是否需要过滤
            if (!this.ledInterface.FeiKongIsMatch) {
                // 转发到LED显示屏
                this.backendSocket.write(packet);
            }
        }
    }

    // 字节匹配检查
    matchBytes(data, pattern) {
        if (data.length < pattern.length) {
            return false;
        }

        for (let i = 0; i < pattern.length; i++) {
            if (data[i] !== pattern[i]) {
                return false;
            }
        }
        return true;
    }

    // 关闭连接
    closeConnection() {
        if (this.frontendSocket) {
            this.frontendSocket.destroy();
        }
        if (this.backendSocket) {
            this.backendSocket.destroy();
        }
    }

    // 处理文本内容
    handleTextContent(content) {
        // 检查开始标记
        const startIndex = this.findPattern(content, this.ledInterface.FeiKongStartFlag);
        if (startIndex === -1) {
            return null;
        }

        // 检查结束标记
        const endIndex = this.findPattern(content, this.ledInterface.FeiKongEndFlag);
        if (endIndex === -1) {
            return null;
        }

        // 提取文本内容
        return content.slice(
            startIndex + this.ledInterface.FeiKongStartFlag.length,
            endIndex
        );
    }

    // 查找字节模式
    findPattern(data, pattern) {
        for (let i = 0; i <= data.length - pattern.length; i++) {
            let found = true;
            for (let j = 0; j < pattern.length; j++) {
                if (data[i + j] !== pattern[j]) {
                    found = false;
                    break;
                }
            }
            if (found) {
                return i;
            }
        }
        return -1;
    }

    // 处理内容开始
    handleContentStart() {
        if (!this.ledInterface.FeiKongIsMatch) {
            this.ledInterface.FeiKongIsMatch = true;
        }
        // 发送第一个响应
        const replyData = this.ledInterface.getFeiKongDataContentReplay(0);
        this.frontendSocket.write(Buffer.from(replyData));
    }
}

module.exports = { FrontendHandler };
